package com.logicbus.redis.toolkit;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.anysoft.util.Pair;
import org.apache.commons.lang3.StringUtils;
import com.anysoft.util.IOTools;
import com.logicbus.redis.client.Connection;
import com.logicbus.redis.client.Toolkit;
import com.logicbus.redis.util.SafeEncoder;

/**
 * 信息工具
 * @author yyduan
 * @version 1.6.12.56 [20191226] <br>
 * - 优化信息输出接口
 */
public class InfoTool extends Toolkit {
	protected static Pattern pattern = Pattern.compile("^([^\\:]+):(.*)$");
	public InfoTool(Connection _conn) {
		super(_conn);
	}
	
	public static enum Command {
		INFO;
		public final byte [] raw;		
		Command(){
			raw = SafeEncoder.encode(name());
		}
	}
	
	public void _info(final String section){
		sendCommand(Command.INFO.raw, section);
	}
	
	public String info(final String section){
		_info(section);
		return getBulkReply();
	}	
	
	public void info(final String section,List<Pair<String,String>> result){
		String ret = info(section);
		if (StringUtils.isNotEmpty(ret)){
			BufferedReader reader = new BufferedReader(new StringReader(ret));
			String line = null;
			try{
				while ((line = reader.readLine()) != null){
					Matcher matcher = pattern.matcher(line);
					if (matcher.find()){
						result.add(new Pair.Default<String,String>(matcher.group(1),matcher.group(2)));
					}
				}
			}catch (IOException ex){

			}finally{
				IOTools.close(reader);
			}
		}
	}
	
	public void server(List<Pair<String,String>> result){
		info("server",result);
	}
	
	public void clients(List<Pair<String,String>> result){
		info("clients",result);
	}
	
	public void memory(List<Pair<String,String>> result){
		info("memory",result);
	}
	
	public void persistence(List<Pair<String,String>> result){
		info("persistence",result);
	}
	
	public void stats(List<Pair<String,String>> result){
		info("stats",result);
	}
	
	public void replication(List<Pair<String,String>> result){
		info("replication",result);
	}
	
	public void cpu(List<Pair<String,String>> result){
		info("cpu",result);
	}
	
	public void commandstats(List<Pair<String,String>> result){
		info("commandstats",result);
	}
	
	public void cluster(List<Pair<String,String>> result){
		info("cluster",result);
	}
	
	public void keyspace(List<Pair<String,String>> result){
		info("keyspace",result);
	}
	
	public void all(List<Pair<String,String>> result){
		info("all",result);
	}
	
	public void defaults(List<Pair<String,String>> result){
		info("default",result);
	}
}
